import type { AxiosResponse, ResponseType } from 'axios'
import axios from 'axios'
import { ElMessage } from 'element-plus'

interface HttpConfig {
  url: string
  method: 'POST' | 'PUT' | 'GET' | 'DELETE'
  data?: any
  params?: any
  headers?: any
  responseType?: ResponseType
  onUploadProgress?: () => void
}

interface HttpResponse<T = any> {
  code: number
  data: T
  msg: string
}

export const $https = (config: HttpConfig) => {
  const instance = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout: 60000
  })

  instance.interceptors.request.use(
    (req) => {
      return req
    },
    (error) => {
      ElMessage.error(error)
      return Promise.reject(error)
    }
  )

  instance.interceptors.response.use(
    (response: AxiosResponse) => {
      const res = response.data
      if (res.code !== 200) {
        throw new Error(res.message || '请求失败')
      }
      return res.data
    },
    (error) => {
      return Promise.reject(error)
    }
  )
  return instance(config)
}
